<template>
    <div class="jianzhan-content">
        <Crumb name="装箱单/Packing List"></Crumb>
        <div class="content">
            <el-button type="primary"
                       size="small"
                       class="input"
                       icon="el-icon-plus"
                       @click="openAdd">添加装箱单/Add Packing
                List
            </el-button>
            <el-input v-model="key"
                      size="small"
                      class="input"
                      @input="keyChange"
                      style="display:inline-block;width: 200px;margin-left: 10px;"
                      placeholder="合同号/Contract No"></el-input>
            <div class="table-wrapper">
                <el-table
                        :data="boxList"
                        :row-style="rowStyle"
                        style="width: 100%">
                    <el-table-column
                            header-align="center"
                            align="center"
                            prop="shipInformation"
                            label="Ship Info"
                    >
                    </el-table-column>
                    <el-table-column
                            prop="contractNumber"
                            label="合同号/Contract No"
                            width="180">
                        <!--<template slot-scope="scope">-->
                            <!--<div v-if="scope.row.contractNumber">-->
                                <!--<div v-for="item in scope.row.contractNumber" :key="item">{{item}}</div>-->
                            <!--</div>-->
                        <!--</template>-->
                    </el-table-column>
                    <el-table-column
                            prop="packingOrderNumber"
                            label="装箱号/Packing No"
                            width="180">
                    </el-table-column>
                    <el-table-column
                            prop="batch"
                            label="批次/Batch"
                            width="180">
                    </el-table-column>
                    <el-table-column
                            prop="packingDateStr"
                            label="装箱日期/Date">
                    </el-table-column>
                    <el-table-column
                            label="Operate"
                    >
                        <template slot-scope="scope">
                            <el-button type="primary" size="small" icon="el-icon-edit" @click="openEdit(scope.row,idx)">
                                编辑
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="page">
                    <el-pagination background
                                   :page-size="pageSize"
                                   @current-change="changePage"
                                   layout="prev, pager, next"
                                   :total="total"></el-pagination>
                </div>
            </div>
        </div>
        <Print :partList="selectedPartList" :box="box" :dialogVisible="print1Visible"
               @close="print1Visible = false"></Print>
        <Print2 :partList="selectedPartList" :box="box" :dialogVisible="print2Visible"
                @close="print2Visible = false"></Print2>
        <el-dialog
                title="装箱"
                :visible.sync="dialogVisible"
                width="100%"
        >
            <el-form ref="form" :model="box" label-width="200px" inline style="text-align: left">
                <el-form-item label="合同号/Contract No">
                    <el-select v-model="box.consignmentIdList"
                               filterable
                               placeholder="寄售合同"
                               size="small"
                               multiple
                               @change="consignmentChange">
                        <el-option
                                v-for="item in consignmentList"
                                :key="item.id"
                                :label="item.contractNumber"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="批次/Batch">
                    <el-select v-model="box.batch" placeholder="批次" size="small">
                        <el-option label="A" value="A"></el-option>
                        <el-option label="A2" value="A2"></el-option>
                        <el-option label="B" value="B"></el-option>
                        <el-option label="B2" value="B2"></el-option>
                        <el-option label="C" value="C"></el-option>
                        <el-option label="C2" value="C2"></el-option>
                        <el-option label="D" value="D"></el-option>
                        <el-option label="D2" value="D2"></el-option>
                        <el-option label="E" value="E"></el-option>
                        <el-option label="F" value="F"></el-option>
                        <el-option label="G" value="G"></el-option>
                        <el-option label="H" value="H"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="箱号/Package No.">
                    <el-input v-model="box.packingOrderNumber" placeholder="装箱单号" size="small"></el-input>
                </el-form-item>
                <el-form-item label="日期/Date:">
                    <el-date-picker v-model="box.packingDateStr" type="date" placeholder="装箱时间"
                                    value-format="yyyy-MM-dd" size="small"></el-date-picker>
                </el-form-item>
                <el-form-item label="长×宽×高/L×W×H(mm):">
                    <el-input v-model="box.lwh" placeholder="长宽高" size="small"></el-input>
                </el-form-item>
                <el-form-item label="  净重/Net Weight(Kg):">
                    <el-input v-model="box.netWeight" placeholder="净重" size="small"></el-input>
                </el-form-item>
                <el-form-item label="  毛重/Gross Weight(Kg):">
                    <el-input v-model="box.grossWeight" placeholder="毛重" size="small"></el-input>
                </el-form-item>
                <el-form-item label="  体积/Volume(m3):">
                    <el-input v-model="box.volume" placeholder="体积" size="small"></el-input>
                </el-form-item>
                <el-form-item label="包装类别/Package:">
                    <el-input v-model="box.packingCategory" placeholder="包装类别" size="small"></el-input>
                </el-form-item>

            </el-form>
            <div class="table" style="text-align: left">
                <el-input
                        prefix-icon="el-icon-search"
                        v-model="searchKey"
                        size="mini"
                        style="width: 50%;display: block"
                        placeholder="Search part no"></el-input>
                <el-table
                        :data="partList.filter(item => item.partsNumber.includes(searchKey))"
                        stripe
                        border
                        height="500px"
                        style="width:50%;font-size: 11px;display: inline-block">
                    <el-table-column
                            type="index"
                    >
                    </el-table-column>
                    <el-table-column
                            prop="partsNumber"
                            label="配件编号/Part No"
                    >
                    </el-table-column>
                    <el-table-column
                            prop="denomination"
                            label="中文"
                            width="180">
                    </el-table-column>
                    <el-table-column
                            prop="designation"
                            label="English">
                    </el-table-column>
                    <el-table-column
                            prop="unPackingQuantity"
                            label="数量/Qty">
                        <template slot-scope="scope">
                            <el-input-number v-model="scope.row.unPackingQuantity" size="small"
                                             step="1"></el-input-number>
                        </template>
                    </el-table-column>
                    <el-table-column
                            width="70px"
                            label="Operate"
                    >
                        <template slot-scope="scope">
                            <el-button type="warning" size="mini" @click="selectData(scope.row,scope.$index)">
                                <i class="el-icon-arrow-right"></i>
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-table
                        :data="selectedPartList"
                        stripe
                        border
                        height="500px"
                        style="width:50%;font-size: 11px;display: inline-block">
                    <el-table-column
                            type="index"
                    >
                    </el-table-column>
                    <el-table-column
                            prop="partsNumber"
                            label="配件编号/Part No"
                    >
                    </el-table-column>
                    <el-table-column
                            prop="denomination"
                            label="中文"
                            width="180">
                    </el-table-column>
                    <el-table-column
                            prop="designation"
                            label="English">
                    </el-table-column>
                    <el-table-column
                            prop="unPackingQuantity"
                            label="数量/Qty">
                        <template slot-scope="scope">
                            <el-input-number v-model="scope.row.unPackingQuantity" size="small"
                                             step="1"></el-input-number>
                        </template>
                    </el-table-column>
                    <el-table-column
                            width="70px"
                            label="Operate"
                    >
                        <template slot-scope="scope">
                            <el-button type="warning" size="mini" @click="unSelectData(scope.row,scope.$index)">
                                <i class="el-icon-arrow-left"></i>
                            </el-button>
                        </template>
                    </el-table-column>
                    <div class="page">
                        <el-pagination background
                                       @current-change="changePage"
                                       :page-size="pageSize"
                                       layout="prev, pager, next"
                                       :total="total"></el-pagination>
                    </div>

                </el-table>
            </div>
            <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">Cancel</el-button>
            <el-button type="primary" @click="submitForm">Confirm</el-button>
                <el-button type="primary" @click="print1">Print1</el-button>
                            <el-button type="primary" @click="print2">Print2</el-button>
          </span>
        </el-dialog>

    </div>
</template>

<script>
    import Crumb from '../../components/common/crumb'
    import {getBoxList, addBoxList, modBoxList, getConsignmentDetail, getBoxListDetail} from "../../api/shanxi";
    import {getContractList} from "../../api/contract";
    import authMixins from "../../util/authMixins"
    import {ERROR_OK} from "../../util/config";
    import Print from './print'
    import Print2 from './print2'
    import mixins from '../../util/mixins'
    import {debounce} from '../../util/index'

    export default {
        name: "consignment",
        mixins: [authMixins, mixins],
        components: {
            Print: Print,
            Print2,
            Crumb,
        },
        data() {
            return {
                box: {
                    grossWeight: '', //毛重
                    lwh: '',   //长宽高
                    netWeight: '', //净重
                    packingCategory: '', //包装类别
                    volume: '',  //体积
                    batch: '', //发运批次
                    packingOrderNumber: '',//装箱单号
                    packingDateStr: '',//装箱日期
                    consignmentIdList: []//寄售合同id列表
                },
                lastIdList: [],
                consignmentList: [],
                dialogVisible: false,
                boxList: [],
                key: '',
                searchKey: '',
                total: 0,
                partList: [],
                selectedPartList: [],//选中的配件
                print1Visible: false,
                print2Visible: false
            }
        },
        created() {
            this._getBoxList();
        },
        methods: {
            keyChange() {
                debounce(this._getBoxList)()
            },
            rowStyle({row}) {
                if (row.saveOrConfirm === '1') {
                    return {
                        background: 'lightgreen',
                    }
                } else if (row.saveOrConfirm === '0') {
                    return {
                        background: '#ddd',
                    }
                } else {
                    return {}
                }
            },
            print1() {
                this.print1Visible = true;
            },
            print2() {
                this.print2Visible = true;
            },
            consignmentChange(v) {
                if (v.length > this.lastIdList.length) {  //新增了
                    this._getConsignmentDetail(v[v.length - 1]);
                }
                if (v.length <= this.lastIdList.length) {
                    const id = this.findDeleteItem(v, this.lastIdList);
                    this._deleteItem(id);
                }
                this.lastIdList = v;
            },
            _deleteItem(id) {
                if (this.partList.length) {
                    const list = this.partList.filter(item => item.consignmentOrderId !== id);
                    this.partList = list;
                }
                if (this.selectedPartList.length) {
                    const list1 = this.selectedPartList.filter(item => item.consignmentOrderId !== id);
                    this.selectedPartList = list1;
                }
            },
            findDeleteItem(arr1, arr2) {
                let id;
                if (arr2.length === 1) {
                    return arr2[0];
                }
                arr2.forEach(item => {
                    if (arr1.indexOf(item) < 0) {
                        id = item;
                    }
                });
                return id;
            },
            async _getConsignmentDetail(id) {
                const {status, data} = await getConsignmentDetail(id);
                if (status === ERROR_OK) {
                    this.partList = this.partList.concat(data);
                }
            },
            async _getConsignmentList() {
                const {status, data} = await getContractList();
                if (status === ERROR_OK) {
                    this.consignmentList = data;
                } else {
                    this.$message.error('获取寄售合同信息失败');
                }
            },
            changePage(page){
                this.pageNum = page
                this._getBoxList()
            },
            async _getBoxList() {
                const {status, data} = await getBoxList(
                   this.pageNum, this.key
                );
                if (status === ERROR_OK) {
                    this.boxList = data.list;
                    this.total = data.total
                } else {
                    this.$message.error('No data');
                    this.boxList = []
                }
            },
            openAdd() {
                this.dialogVisible = true;
                this.clear();
                if (!this.consignmentList.length) {
                    this._getConsignmentList();
                }
            },
            clear() {
                this.box = {
                    grossWeight: '', //毛重
                    lwh: '',   //长宽高
                    netWeight: '', //净重
                    packingCategory: '', //包装类别
                    volume: '',  //体积
                    batch: '', //发运批次
                    packingOrderNumber: '',//装箱单号
                    packingDateStr: '',//装箱日期
                    consignmentIdList: []//寄售合同id列表
                };
                this.lastIdList = [];
                this.partList = [];
                this.selectedPartList = [];
            },
            async openEdit(row) {
                this.clear();
                if (!this.consignmentList.length) {
                    this._getConsignmentList();
                }
                if (row.contractNumberId && row.contractNumberId.length) {
                    row.contractNumberId.forEach(item => {
                        this._getConsignmentDetail(item);
                    })
                }
                this._getBoxListDetail(row);
                this.dialogVisible = true;
            },
            async _getBoxListDetail(row) {
                const {status, data} = await getBoxListDetail(row.id);
                if (status === ERROR_OK) {
                    this.box = {
                        id: data.id,
                        batch: data.batch, //发运批次
                        grossWeight: data.grossWeight,
                        volume: data.volume,
                        packingCategory: data.packingCategory,
                        lwh: data.lwh,
                        netWeight: data.netWeight,
                        packingOrderNumber: data.packingOrderNumber,//装箱单号
                        packingDateStr: data.packingDateStr,//装箱日期
                        contractNumber: data.contractNumber,
                        consignmentIdList: data.contractNumberId || []//寄售合同id列表
                    }
                    const list = data.packingDetailVoList.map(item => {
                        return {
                            ...item, unPackingQuantity: item.quantity
                        }
                    });
                    this.selectedPartList = list;
                    this.lastIdList = data.contractNumberId || [];
                } else {
                    this.$message.error('获取装箱单详情失败');
                }
            },
            async submitForm() {
                const {batch, packingOrderNumber, packingDateStr, id, lwh, netWeight, grossWeight, packingCategory, volume} = this.box;
                let packingDetails = this.selectedPartList.map(item => {
                    return {
                        partsId: item.partsId,
                        packingQuantity: item.unPackingQuantity,
                        consignmentOrderId: item.consignmentOrderId,
                        batch: this.box.batch
                    }
                });
                packingDetails = JSON.stringify(packingDetails);
                if (this.box.id) {
                    //修改
                    const {status, msg} = await modBoxList({
                        id,
                        batch,
                        packingOrderNumber,
                        packingDateStr,
                        netWeight,
                        lwh,
                        grossWeight,
                        packingCategory,
                        volume,
                        packingDetails
                    });
                    if (status === ERROR_OK) {
                        this._getBoxList();
                        this.$message.success('修改成功');
                        this.clear();
                        this.dialogVisible = false;
                    } else {
                        this.$notify.error(msg);
                    }
                } else {
                    // 新增
                    const {status, msg} = await addBoxList({
                        batch,
                        packingOrderNumber,
                        packingDateStr,
                        netWeight,
                        grossWeight,
                        lwh,
                        packingCategory,
                        volume,
                        packingDetails
                    });
                    if (status === ERROR_OK) {
                        this._getBoxList();
                        this.$message.success('新增成功');
                        this.clear();
                        this.dialogVisible = false;
                    } else {
                        this.$notify.error(msg);
                    }
                }
            },

            selectData(row) {
                const index = this.partList.findIndex(item => item.partsNumber === row.partsNumber);
                const target = this.partList[index];
                this.partList.splice(index, 1);
                this.selectedPartList.push(target)
            },
            unSelectData(row) {
                const index = this.selectedPartList.findIndex(item => item.partsNumber === row.partsNumber);
                const target = this.selectedPartList[index];
                this.selectedPartList.splice(index, 1);
                this.partList.push(target)
            }

        }
    }
</script>

<style scoped lang="scss">
    @import "../../css/mixins";

    .content {
        @include content
    }

    .label-btn {
        cursor: pointer;
        height: 30px;
        line-height: 30px;
        text-align: center;
        color: white;
        background-color: #409eff;
        border-radius: 3px;
        padding: 5px 15px;
        display: block;
        width: 120px;
    }

    .warning {
        color: #fff;
        font-weight: bold;
        background-color: #c60023;
    }

    .confirm {
        background: lightgreen;
        color: #fff;
    }

    .save {
        background: orange;
        color: #fff;
    }
</style>